package com.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class IPInterceptor implements HandlerInterceptor {

    //@Autowired
    //private ProjectTableDao projectTableDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress=IPUtils.getRealIP(request);//request.getRemoteAddr();//request.getHeader("Host");//
        System.out.println(ipAddress);
        List<String> listIps = getListIps();
        if (listIps == null || listIps.size() == 0 || !listIps.contains(ipAddress) ){
            response.getWriter().print("Ip forbidden!!!");
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    	
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
    public static List<String> readFileByLines(String fileName) {  
    	List<String> result  = new ArrayList<>();
        File file = new File(fileName);  
        BufferedReader reader = null;  
        try {  
            //System.out.println("以行为单位读取文件内容，一次读一整行：");  
            reader = new BufferedReader(new FileReader(file));  
            String tempString = null;  
            int line = 1;  
            // 一次读入一行，直到读入null为文件结束  
            while ((tempString = reader.readLine()) != null) {  
                // 显示行号  
                //System.out.println("line " + line + ": " + tempString);  
                result.add(tempString);
                line++;  
            }  
            reader.close();  
            //return result;
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (reader != null) {  
                try {  
                    reader.close();  
                } catch (IOException e1) {  
                	
                }  
            }  
        }
		return result;  
    }  
    public List<String> getListIps(){
        
        String rootPath = System.getProperty("user.dir").replace("\\", "/");
        List<String> result  = readFileByLines(rootPath+"/whiteList");
       
        return result;
    }


}
